package org.wkg.lesson05;

public class Demo_505 {

    public static void main(String[] args) throws InterruptedException {
        // 初始化累加对象
        Counter505 counter = new Counter505();

        // 创建两个线程对一个变量进时累加
        Thread t1 = new Thread(() -> {
            // 5万次
            for (int i = 0; i < 50000; i++) {
                counter.increase1();
            }
        });

        // 线程2
        Thread t2 = new Thread(() -> {
            // 5万次
            for (int i = 0; i < 50000; i++) {
                counter.increase2();
            }
        });

        // 启动线程
        t1.start();
        t2.start();

        // 等待线程执行完成
        t1.join();
        t2.join();

        // 查看运行结果
        System.out.println("count = " + counter.count);
    }
}

class Counter505 {
    int count = 0;

    Object lock = new Object();

    public void increase(){
        synchronized (lock){
            increase1();
        }
    }


    public void increase1(){
        synchronized (lock){
            increase2();
        }
    }

    public void increase2(){
        synchronized (lock){
            count++;
        }
    }



}